import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zchope_student/apis.dart';
import 'package:zchope_student/beans/UpdateBean.dart';
import 'package:zchope_student/beans/eventbean.dart';
import 'package:zchope_student/beans/userInfoBean.dart';
import 'package:zchope_student/mine/mine.dart';
import 'package:zchope_student/shouye/firstpage.dart';
import 'package:zchope_student/utils/mydio.dart';
import 'package:zchope_student/utils/utils.dart';

import '../const.dart';
import 'course.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with SingleTickerProviderStateMixin {
  var titles = ['资讯', '服务', '我的'];
  int _currentIndex = 0;
  String nickName;
  String title = '客户';
  String memberBh = '';
  List<BottomNavigationBarItem> icons = new List();
  var _mySubscription;
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  var _controller = PageController(
    initialPage: 0,
  );

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  _getLocation() async {
    if (await requestPermission()) {
      final location = await AmapLocation.fetchLocation();

      var city = location.city;
      var adCode = location.adCode;

      city.then((String s) {
        print('city!!!!!$s');
      });
      adCode.then((String s) {
        eventBus.fire(EventBean(title: Const.EVENT_LOCATION, content: s));
      });
    }
  }

@override
void initState() {
  _getLocation();
  _memberInfo();

  PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
    var version = packageInfo.version;
    MyDio.getInstance().clearInstance();
    MyDio.getInstance(url: Const.UPDATEURL).get(Apis.update, (data) async {
      print(data);
      if (data['code'] == 200) {
        UpdateBean updateBean = UpdateBean.fromJson(data['data']);
        if (updateBean.version != version) {
          Utils.getInstance().updateApp('http://192.168.1.132:8081/app-release.apk', true);
        }
      }
    });
  });

}

_memberInfo() async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  memberBh = sp.getString('bh');
  if (memberBh != null) {
    Map<String, dynamic> dataBind = Map();
    dataBind['memberBh'] = memberBh;
    MyDio.getInstance().clearInstance();
    MyDio.getInstance().get(Apis.memberInfo + memberBh, (data) async {
      print(data);
      if (data['resultCode'] == 0) {
        UserInfoBean _userInfoBean = UserInfoBean.fromJson(data['record']);
        sp.setString(Const.PERSON_NUM, _userInfoBean.personNum);
        sp.setString(Const.UUID, _userInfoBean.recordBh);
        sp.setString('loginName', _userInfoBean.loginName);
        sp.setString('nickName', _userInfoBean.nickName);
        sp.setString('photo', _userInfoBean.photo);
        sp.setString(Const.AREA_CODE, _userInfoBean.areacode);
        print('身份证号保存成功');
      }
    });
  }
}


Future<bool> requestPermission() async {
  final permissions = await PermissionHandler().requestPermissions([
    PermissionGroup.location,
    PermissionGroup.sensors,
    PermissionGroup.storage,
  ]);

  if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
    return true;
  } else {
    return false;
  }
}


List<BottomNavigationBarItem> setIcons() {
  icons.clear();
  icons.add(BottomNavigationBarItem(
      icon: _currentIndex == 0
          ? Icon(Icons.home, color: Const.gold)
          : Icon(Icons.home, color: Const.grey),
      title: Text(
        titles[0],
      )));
  icons.add(BottomNavigationBarItem(
      icon: _currentIndex == 1
          ? Icon(Icons.drive_eta, color: Const.gold)
          : Icon(Icons.drive_eta, color: Const.grey),
      title: Text(
        titles[1],
      )));
  icons.add(BottomNavigationBarItem(
      icon: _currentIndex == 2
          ? Icon(Icons.person, color: Const.gold)
          : Icon(Icons.person, color: Const.grey),
      title: Text(
        titles[2],
      )));

  return icons;
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    key: _scaffoldkey,
    backgroundColor: Const.black,
    body: PageView(
      controller: _controller,
      children: [FirstPage(), Course(), Mine()],
      physics: NeverScrollableScrollPhysics(),
    ),
    bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        backgroundColor: Const.bar,
        selectedItemColor: Const.gold,
        unselectedItemColor: Const.grey,
        selectedFontSize: 12,
        unselectedFontSize: 12,
        onTap: (index) async {
          title = titles[index];
          _controller.jumpToPage(index);
          setState(() {
            _currentIndex = index;
          });


//            _updateApp('http://issuecdn.baidupcs.com/issue/netdisk/apk/BaiduNetdisk_10.0.116.apk',false);
        },
        type: BottomNavigationBarType.fixed,
        items: setIcons()),
  );
}}
